//
//  WXTrafficViolationsTableViewController.m
//  CarJX
//
//  Created by jxcl on 14-9-17.
//  Copyright (c) 2014年 KK. All rights reserved.
//

#import "WXTrafficViolationsTableViewController.h"
#import "WXIllegalProcessingTableViewCell.h"
#import "WXViolationDetailsTableViewController.h"
#import "CLUIBaseNavigationController.h"
#import "WXContactShopViewController.h"
#import "UIViewController+HttpRequest.h"
#define kBtnFrame CGRectMake(46, 8, 229, 30)
#define kCellIdentifier @"IllegalProcessing"
#define phoneNum @"tel://8004664411"

@interface WXTrafficViolationsTableViewController () <UIAlertViewDelegate>
@property (nonatomic , strong ) NSArray *_violationList;
@end
static int a = 0;

@implementation WXTrafficViolationsTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}


//程序内打电话
- (IBAction)callME:(id)sender {
    UIWebView*callWebview =[[UIWebView alloc] init] ;
    
    // tel:  或者 tel://
    NSURL *telURL =[NSURL URLWithString:phoneNum];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    
    [self.view addSubview:callWebview];
   

}
#pragma mark - 联系商家
- (void)contactShop{
 
    if ([_violationDic allKeys].count <= 0 || _violationDic == nil  ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择具体的违章记录再联系商家" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else {
        if ([Common currenLoginStatus] == NO) {
            CLUIBaseNavigationController *nav = [[CLUIBaseNavigationController alloc]  initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"login"] ];
            [self presentViewController:nav animated:YES completion:nil];
        }else{
            if (![[NSUserDefaults standardUserDefaults] objectForKey:@"addressinfos"]) {
                [self.navigationController.view makeToast:@"您的个人信息没有完善，请到个人中心完善个人资料" duration:2 position:TOP_POINT];
                return;
            }
            WXContactShopViewController *contact =  [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"contact"];
            contact.seletedTraffic = [_violationDic copy];
            CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:contact];
            
            [self.navigationController pushViewController:contact animated:YES];
        }

      
        
    }

    
}

- (void) viewWillAppear:(BOOL)animated{
    if (!_barView) {
        _barView = [[UIView alloc] initWithFrame:CGRectMake(0, 523, 320, 45)];
        _barView.backgroundColor = [UIColor colorWithRed:248 green:248 blue:255 alpha:1.0f];
        UIButton *btn = [[UIButton alloc] initWithFrame:kBtnFrame];
        btn.tag = 421;
        [btn addTarget:self action:@selector(contactShop) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:@"联系商家" forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"paybtn.png"] forState:UIControlStateNormal];
        [_barView addSubview:btn];
        
        [[UIApplication sharedApplication].keyWindow addSubview:_barView];
        
    }else{
        _barView.hidden = NO;
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_barView];
    }
}

- (void) viewWillDisappear:(BOOL)animated{
    _barView.hidden = YES;
    
  //  [[UIApplication sharedApplication].keyWindow sendSubviewToBack:_barView];
}

- (void) responseNotification:(NSNotification *)notificaiton{
    
    //存的id 用于联系商家
    if (!_violationDic) {
        _violationDic = [[NSMutableDictionary   alloc] init];
    }
    
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:(NSDictionary *)notificaiton.object];
    if ([[dic objectForKey:@"repet"] isEqualToString:@"0"]) {

        [_violationDic setObject:dic forKey:[dic objectForKey:@"tag"]];
    }else{
        [_violationDic removeObjectForKey:[dic objectForKey:@"tag"]];
    }
 
 }

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self setTitle:self.carNum];
    [self.tableView registerNib:[UINib nibWithNibName:@"WXIllegalProcessingTableViewCell" bundle:nil] forCellReuseIdentifier:@"IllegalProcessing"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(responseNotification:) name:@"cellSelete" object:nil];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 20, 0)];
    if ([self.identity isEqualToString:@"登陆"]) {
        
        
        [self GETWithContentType:@"imiviolation" params:@{@"car_id" : self.carId} success:^(ResultMy *result) {
            [self.view hideToastActivity];
            __violationList = [result.dictionaryInfo objectForKey:@"violation"];
            [self setNavigationBarRightView: (__violationList == nil)?0:([__violationList count])];
            if ([__violationList count] == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜您,此车辆没有违章记录哦!请继续保持." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 101;
                [alert show];
            }
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            if (error) {
                ResultMy *errorResult = [error.userInfo objectForKey:@"result"];
                NSString *errorstr = errorResult.info[@"error"];
                [self.view makeToast:errorstr];            }
            [self.view hideToastActivity];
            NSLog(@"%@",error.localizedDescription);
            [self setNavigationBarRightView: (__violationList == nil)?0:([__violationList count])];
            
        }];

        [self.view makeToastActivity];
    }
    if([self.identity isEqualToString:@"未登陆"]){
        __violationList = [self.dicInfo objectForKey:@"violation"];
        [self setNavigationBarRightView: (__violationList == nil)?0:([__violationList count])];
        if ([__violationList count] == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜您,此车辆没有违章记录哦!请继续保持." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 101;
            [alert show];
        }
        [self.tableView reloadData];

    }
}
- (void) setNavigationBarRightView:(NSInteger) num{
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor whiteColor];
    label.text = [NSString stringWithFormat:@"共计%d条",num];
    
    label.frame = CGRectMake(0, 0, 60, 40);
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:label];
    self.navigationItem.rightBarButtonItem = right;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [__violationList count];
}

- (void)alertViewCancel:(UIAlertView *)alertView{
   
    
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 101) {
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];

        }
    }
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 93;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   WXIllegalProcessingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IllegalProcessing" forIndexPath:indexPath];
    
    [cell  setSelectionStyle:UITableViewCellSelectionStyleNone];
  //  WXIllegalProcessingTableViewCell *cell = [[WXIllegalProcessingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"IllegalProcessing"];
    
  /*
   address = "\U91d1\U5c71\U53e3";
   agency = "\U5357\U57ce\U5927\U961f";
   content = "\U9a7e\U9a76\U673a\U52a8\U8f66\U8fdd\U53cd\U9053\U8def\U4ea4\U901a\U4fe1\U53f7\U706f\U901a\U884c\U7684";
   id = 2043711;
   legalnum = 1625;
   number = 3610214000203815;
   price = 100;
   score = 6;
   time = "2014-09-05 18:05";
   */
   
    
    cell.tag = 300 + indexPath.row;
    
    NSInteger num = indexPath.row;
    num ++ ;
#warning 这里的字段名大小写和登录后的不一样;
    if ([self.identity isEqualToString:@"登陆"]) {
        [cell setviolationLabel:__violationList[indexPath.row] andNum:num andId:[[__violationList objectAtIndex:indexPath.row]  objectForKey:@"ID"]];
    }else if ([self.identity isEqualToString:@"未登陆"]){
        [cell setHadLoginviolationLabel:__violationList[indexPath.row] andNum:num andId:[[__violationList objectAtIndex:indexPath.row]  objectForKey:@"id"]];
    }
    
    if ([_violationDic objectForKey:[NSString stringWithFormat:@"%d",cell.tag]] != nil) {
         [cell violationBtnRequest:YES];
        
    }else{
 
        [cell violationBtnRequest:NO];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    WXViolationDetailsTableViewController *violation = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"details"];
    if ([self.identity isEqualToString:@"登陆"]) {
        violation.violationID = [[__violationList objectAtIndex:indexPath.row]  objectForKey:@"ID"];
        violation.identity = @"登陆";
    }else if([self.identity isEqualToString:@"未登陆"]){
//        violation.violationID = [[__violationList objectAtIndex:indexPath.row]  objectForKey:@"id"];
        violation.weiZhangDicInfo = [__violationList objectAtIndex:indexPath.row];
        violation.identity = @"未登陆";
    }
    violation.carNum = self.carNum;
    CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:violation];
    

    [self.navigationController pushViewController:violation animated:YES];
}
 


@end
